package com.example.wacoffee_manage.controller;

import cn.hutool.json.JSONUtil;
import com.example.wacoffee_manage.Service.goodService;
import com.example.wacoffee_manage.common.PageResult;
import com.example.wacoffee_manage.pojo.Good;
import com.example.wacoffee_manage.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goods")
public class goodController {
    @Autowired
    private goodService goodService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping
    public Result getAllGoods(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false, name = "name") String name,
            @RequestParam(required = false, name = "minPrice") Integer minPrice,
            @RequestParam(required = false, name = "maxPrice") Integer maxPrice,
            @RequestParam(required = false, name = "supplyName") String supplyName) {
        Good good = new Good();
        good.setName(name);
        good.setMinPrice(minPrice);
        good.setMaxPrice(maxPrice);
        good.setSupplyName(supplyName);
        good.setPage(currentPage);
        good.setPageSize(pageSize);
        PageResult goods = goodService.getAllGoods(good);
        return Result.success(goods);
    }

    @PostMapping
    public Result addGood(@RequestBody Good good) {
        goodService.add(good);
        List<Good> goods = goodService.getAllGood();
        String jsonStr = JSONUtil.toJsonStr(goods);
        stringRedisTemplate.opsForValue().set("goods", JSONUtil.toJsonStr(jsonStr));
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable int id) {
        Good good = goodService.getById(id);
        return Result.success(good);
    }

    @PutMapping
    public Result update(@RequestBody Good good){
        goodService.update(good);
        List<Good> goods = goodService.getAllGood();
        String jsonStr = JSONUtil.toJsonStr(goods);
        stringRedisTemplate.opsForValue().set("goods", JSONUtil.toJsonStr(jsonStr));
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam int id) {
        goodService.delete(id);
        List<Good> goods = goodService.getAllGood();
        String jsonStr = JSONUtil.toJsonStr(goods);
        stringRedisTemplate.opsForValue().set("goods", JSONUtil.toJsonStr(jsonStr));
        return Result.success();
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Long> ids){
        goodService.deleteBatch(ids);
        return Result.success();
    }
}